import datetime

from django.db import models
from django.db.models import Max

from base.models import CustomSupplier
from finance.models import CapitalAccount
from users.models import UserInfo


class PointType(models.Model):
    """积分类型"""
    id = models.IntegerField(verbose_name='编号', primary_key=True)
    name = models.CharField(verbose_name='积分名称', max_length=32, blank=True, null=True)
    remark = models.CharField(verbose_name='备注', max_length=128, blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '积分类型'
        verbose_name_plural = verbose_name
        ordering = ["id"]


class Recharge(models.Model):
    """客户充值"""
    CATE = (
        (0, '充值'),
        # (1, '优惠卡'),
    )
    STATUS = (
        (0, '有效'),
        (1, '已使用'),
        (2, '无效')
    )
    code = models.CharField(verbose_name='充值单编号', max_length=24, null=True, blank=True)
    customer = models.ForeignKey(CustomSupplier, verbose_name='客户', on_delete=models.CASCADE, null=True, blank=True, db_constraint=False)
    account = models.ForeignKey(to=CapitalAccount, verbose_name='收款账号', on_delete=models.PROTECT,
                                db_constraint=False, blank=True, null=True)
    category = models.IntegerField(verbose_name='类型', choices=CATE, blank=True, null=True)
    money = models.FloatField(verbose_name='充值金额/优惠卡金额', blank=True, null=True)
    active_point = models.FloatField(verbose_name='活动积分', blank=True, null=True)
    member_point = models.FloatField(verbose_name='会员积分', blank=True, null=True)
    status = models.IntegerField(verbose_name='状态', choices=STATUS, blank=True, null=True)
    remark = models.CharField(verbose_name='备注', max_length=128, blank=True, null=True)
    user = models.ForeignKey(to=UserInfo, verbose_name='操作人', blank=True, null=True, on_delete=models.SET_NULL,
                             db_constraint=False)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.customer.name

    class Meta:
        verbose_name = '客户充值'
        verbose_name_plural = verbose_name
        ordering = ["-id"]

    @classmethod
    def get_max_code(cls):
        date = datetime.datetime.now().strftime('KHCZ%Y%m%d')
        max_code = cls.objects.filter(code__startswith=date).aggregate(max_code=Max("code"))
        max_value = max_code['max_code']
        if max_value is None:
            num = '0001'
            code = '{0}{1}'.format(date, num)
            return code
        else:
            num = str(int(max_value[-4:]) + 1).rjust(4, '0')
            code = '{0}{1}'.format(date, num)
            return code

    def save(self, *args, **kwargs):
        if self.category == 0 and (self.code == "" or self.code is None):
            self.code = self.__class__.get_max_code()

        return super().save(*args, **kwargs)


class HistoryPoint(models.Model):
    """客户历史积分"""
    customer = models.ForeignKey(CustomSupplier, verbose_name='客户', on_delete=models.CASCADE, null=True, blank=True, db_constraint=False)
    active_point = models.FloatField(verbose_name='活动积分', blank=True, null=True)
    member_point = models.FloatField(verbose_name='会员积分', blank=True, null=True)
    consume_point = models.FloatField(verbose_name='消费积分', blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.customer.name

    class Meta:
        verbose_name = '客户历史积分'
        verbose_name_plural = verbose_name
        ordering = ["-id"]


class PointConsume(models.Model):
    """积分消费记录"""
    CATE = (
        (0, '活动积分'),
        (1, '会员积分'),
        (2, '消费积分')
    )
    customer = models.ForeignKey(CustomSupplier, verbose_name='客户', on_delete=models.CASCADE, null=True, blank=True, db_constraint=False)
    code = models.CharField(verbose_name='单据号', max_length=32, blank=True, null=True)
    category = models.IntegerField(verbose_name='类型', choices=CATE, blank=True, null=True)
    point = models.FloatField(verbose_name='积分', blank=True, null=True)
    user = models.ForeignKey(to=UserInfo, verbose_name='操作人', blank=True, null=True, on_delete=models.SET_NULL,
                             db_constraint=False)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.code

    class Meta:
        verbose_name = '客户积分消费'
        verbose_name_plural = verbose_name
        ordering = ["-id"]
